from typing import List

from ioservice.common.mongo import insert_models, insert_one_model, update_one_model_by_id, fake_delete_models_by_ids, \
    find_many_models, count_documents, check_models_exists_by_ids, aggregate_models
from ioservice.const import business_col, business_counter
from ioservice.objectcode import generate_object_code, bulk_generate_object_code
from models.business import Business, business_types
from utils.dateutil import date_now


# dao 方法


async def list_all_business_types():
    return business_types


async def insert_one_business(business: Business):
    business.set_ocode(await generate_object_code(business_counter))
    business.create_time = date_now()
    insert_id = await insert_one_model(business_col, business)
    return insert_id


async def bulk_insert_businesses(businesses: List[Business]):
    ocodes = await bulk_generate_object_code(business_counter, len(businesses))
    for ocode, b in zip(ocodes, businesses):
        b.set_ocode(ocode)
        b.create_time = date_now()
    inserted_ids = await insert_models(business_col, businesses)
    return inserted_ids


async def update_one_business(business_id: str, business: Business):
    business.update_time = date_now()
    modified_num = await update_one_model_by_id(business_col, business_id, business)
    return modified_num


async def delete_many_businesses_by_ids(business_ids: List[str]):
    deleted_num = await fake_delete_models_by_ids(business_col, business_ids)
    return deleted_num


async def find_businesses_by_query(query, sort=None, offset=None, size=None, fields=None):
    return await find_many_models(business_col, Business, query, sort, offset, size, fields)


async def count_businesses(query):
    return await count_documents(business_col, query)


async def check_businesses_exist_by_ids(ids):
    return await check_models_exists_by_ids(business_col, ids)


async def aggregate_businesses(pipeline):
    businesses = await aggregate_models(business_col, pipeline, Business)
    return businesses
